﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Diagnostics;

namespace FileBrowser
{
    public partial class Form1 : Form
    {
        private string currentDirectory;
        private readonly string userDirectory;
        private System.Windows.Forms.ImageList imageList1;
        private System.Windows.Forms.StatusStrip statusStrip1;

        public Form1()
        {
            InitializeComponent();
            userDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            InitializeImageList();
            LoadDirectories(userDirectory);
        }

        private void InitializeImageList()
        {
            imageList1.ImageSize = new Size(16, 16);
            try
            {
                // 加载文件夹图标（系统图标）
                using (Icon folderIcon = Icon.ExtractAssociatedIcon(
                    Path.Combine(Environment.SystemDirectory, "shell32.dll")))
                {
                    imageList1.Images.Add(folderIcon);
                }
                // 加载XML图标（假设xml.ico在输出目录）
                using (Icon xmlIcon = new Icon("xml.ico"))
                {
                    imageList1.Images.Add(xmlIcon);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"图标加载失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            listViewFiles.SmallImageList = imageList1;
        }

        private void LoadDirectories(string path)
        {
            try
            {
                treeViewDirectories.BeginUpdate();
                treeViewDirectories.Nodes.Clear();
                TreeNode rootNode = new TreeNode(Path.GetFileName(path));
                rootNode.Tag = path;
                rootNode.ImageIndex = 0;
                rootNode.SelectedImageIndex = 0;
                treeViewDirectories.Nodes.Add(rootNode);
                LoadSubdirectories(rootNode);
                treeViewDirectories.EndUpdate();
                treeViewDirectories.ExpandAll();
                currentDirectory = path;
                UpdateFileList(path);
            }
            catch (Exception ex)
            {
                statusStrip1.Text = $"加载目录错误: {ex.Message}";
            }
        }

        private void LoadSubdirectories(TreeNode parentNode)
        {
            string parentPath = (string)parentNode.Tag;
            try
            {
                foreach (string dir in Directory.GetDirectories(parentPath))
                {
                    try
                    {
                        TreeNode childNode = new TreeNode(Path.GetFileName(dir));
                        childNode.Tag = dir;
                        childNode.ImageIndex = 0;
                        childNode.SelectedImageIndex = 0;
                        parentNode.Nodes.Add(childNode);
                        LoadSubdirectories(childNode);
                    }
                    catch { } // 忽略无法访问的目录
                }
            }
            catch { }
        }

        private void treeViewDirectories_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node != null)
            {
                string selectedPath = (string)e.Node.Tag;
                UpdateFileList(selectedPath);
            }
        }

        private void UpdateFileList(string path)
        {
            try
            {
                listViewFiles.BeginUpdate();
                listViewFiles.Items.Clear();
                currentDirectory = path;
                statusStrip1.Text = $"当前目录: {path}";

                // 添加文件夹
                foreach (string dir in Directory.GetDirectories(path))
                {
                    FileInfo fi = new FileInfo(dir);
                    ListViewItem item = CreateListViewItem(fi, 0);
                    listViewFiles.Items.Add(item);
                }

                // 添加文件
                foreach (string file in Directory.GetFiles(path))
                {
                    FileInfo fi = new FileInfo(file);
                    int imageIndex = fi.Extension.Equals(".xml", StringComparison.OrdinalIgnoreCase) ? 1 : 0;
                    ListViewItem item = CreateListViewItem(fi, imageIndex);
                    listViewFiles.Items.Add(item);
                }

                listViewFiles.EndUpdate();
            }
            catch (Exception ex)
            {
                statusStrip1.Text = $"更新文件列表错误: {ex.Message}";
            }
        }

        private ListViewItem CreateListViewItem(FileInfo fi, int imageIndex)
        {
            ListViewItem item = new ListViewItem(fi.Name);
            item.SubItems.Add(fi.Extension.TrimStart('.'));
            item.SubItems.Add(fi.Length == 0 ? "0 B" : $"{fi.Length / 1024:N0} KB");
            item.SubItems.Add(fi.LastWriteTime.ToString("yyyy-MM-dd HH:mm"));
            item.ImageIndex = imageIndex;
            return item;
        }

        private void listViewFiles_DoubleClick(object sender, EventArgs e)
        {
            if (listViewFiles.SelectedItems.Count == 0) return;
            string selectedFile = Path.Combine(currentDirectory, listViewFiles.SelectedItems[0].Text);

            if (Path.GetExtension(selectedFile).Equals(".xml", StringComparison.OrdinalIgnoreCase))
            {
                ShowXmlContent(selectedFile);
            }
            else
            {
                OpenFile(selectedFile);
            }
        }

        private void ShowXmlContent(string xmlPath)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(xmlPath);
                StringBuilder content = new StringBuilder();
                content.AppendLine("XML 结构解析：");
                TraverseXmlNode(doc.DocumentElement, 0, content);
                MessageBox.Show(content.ToString(), "XML 内容", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"解析错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void TraverseXmlNode(XmlNode node, int level, StringBuilder content)
        {
            string indent = new string(' ', level * 4);
            content.AppendLine($"{indent}<{node.Name}{GetAttributesString(node)}>");
            if (!string.IsNullOrEmpty(node.InnerText.Trim()))
            {
                content.AppendLine($"{indent}  Text: {node.InnerText.Trim()}");
            }
            foreach (XmlNode child in node.ChildNodes)
            {
                TraverseXmlNode(child, level + 1, content);
            }
            content.AppendLine($"{indent}</{node.Name}>");
        }

        private string GetAttributesString(XmlNode node)
        {
            StringBuilder attrs = new StringBuilder();
            foreach (XmlAttribute attr in node.Attributes)
            {
                attrs.Append($" {attr.Name}=\"{attr.Value}\"");
            }
            return attrs.ToString();
        }

        private void OpenFile(string filePath)
        {
            try
            {
                Process.Start(new ProcessStartInfo(filePath) { UseShellExecute = true });
            }
            catch (Exception ex)
            {
                MessageBox.Show($"无法打开文件: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void toolStripMenuItemExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void toolStripMenuItemRefresh_Click(object sender, EventArgs e)
        {
            if (treeViewDirectories.SelectedNode != null)
            {
                string selectedPath = (string)treeViewDirectories.SelectedNode.Tag;
                LoadDirectories(selectedPath);
            }
        }

        private void toolStripButtonBack_Click(object sender, EventArgs e)
        {
            string parentPath = Directory.GetParent(currentDirectory)?.FullName;
            if (!string.IsNullOrEmpty(parentPath))
            {
                TreeNode parentNode = FindNodeByPath(treeViewDirectories.Nodes, parentPath);
                if (parentNode != null)
                {
                    treeViewDirectories.SelectedNode = parentNode;
                    treeViewDirectories_AfterSelect(sender, new TreeViewEventArgs(parentNode));
                }
            }
        }

        private TreeNode FindNodeByPath(TreeNodeCollection nodes, string targetPath)
        {
            foreach (TreeNode node in nodes)
            {
                if ((string)node.Tag == targetPath)
                    return node;
                TreeNode found = FindNodeByPath(node.Nodes, targetPath);
                if (found != null)
                    return found;
            }
            return null;
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            if (listViewFiles.Columns.Count > 0)
            {
                listViewFiles.Columns[0].Width = listViewFiles.Width / 3;
                listViewFiles.Columns[1].Width = listViewFiles.Width / 6;
                listViewFiles.Columns[2].Width = listViewFiles.Width / 6;
                listViewFiles.Columns[3].Width = listViewFiles.Width / 3;
            }
        }

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(mainForm: new Form1());
        }
    }
}